{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b4c989fa",
   "metadata": {},
   "source": [
    "### 匿名函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6b9e9588",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 4, 9, 16, 25, 36, 49, 64, 81]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(map(lambda x: x * x, list(range(1,10))))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be6cff0f",
   "metadata": {},
   "source": [
    "可以发现lambda x: x * x实际上就是："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2258c94f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(x):\n",
    "    return x * x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35140c42",
   "metadata": {},
   "source": [
    "lambda表示匿名函数，冒号前面的x表示函数参数。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "662b86d7",
   "metadata": {},
   "source": [
    "匿名函数有个限制，就是只能有一个表达式，不用写return，返回值就是该表达式的结果"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6027e54d",
   "metadata": {},
   "source": [
    "匿名函数有个好处，因为函数没有名字，不必担心函数名冲突。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f762b955",
   "metadata": {},
   "source": [
    "同样，也能把匿名函数作为返回值返回。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c4aa1bd6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def build(x, y):\n",
    "    return lambda: x * x + y * y\n",
    "f = build(1,2)\n",
    "f()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca39a412",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d89fe83",
   "metadata": {},
   "source": [
    "只有一些简单的情况下可以使用匿名函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9df35d13",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
